package com.bbx.aliyunapi.config;

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class EcsClientConfig {


    @Value("${aliyun.ecs.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.ecs.accessSecret}")
    private String accessSecret;

    private static Config config;

    private static Client client;

    private EcsClientConfig() { }


    public Client getClient() {
        if (config== null) {
            initClient();
        }
        return client;
    }


    private void initClient() {
        log.info("[{}]", "init Client ~~~~~~~~~~~~~~~~~~~~~~~~~~~");
         config = new Config().setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessSecret);
        // 访问的域名
        EcsClientConfig.config.endpoint = "ecs-cn-hangzhou.aliyuncs.com";
        try {
            client = new Client(EcsClientConfig.config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取 安全组的区域 ID
     *
     * @return
     * @throws Exception
     */
    public static String getRegionId(Client client) throws Exception {
        DescribeRegionsRequest describeRegionsRequest = new DescribeRegionsRequest();
        DescribeRegionsResponse describeRegionsResponse = client.describeRegions(describeRegionsRequest);
        log.info("describeRegionsResponse[{}]", describeRegionsResponse);
        String regionId = describeRegionsResponse
                .getBody()
                .getRegions()
                .getRegion()
                .get(0)
                .getRegionId();
        return regionId;
    }

}
